<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlixCx0RpE2HxChFL2D1e313caOhGAreljHgm0aK6IN+SQgeQICTEf2JFY9NtNcTRKAhhGyDhmobEPDDvXJSBaTo7rLdZl1C2Js3R0ni3NauXrlVqT6FIWC9sfcZOyNj5UEvJ0h3f6Oc7DLG0pTSCfR2poZaVdlWB5oTItbV0NolT74Mh9bqJL+QAs+xhlSPrvCf4v33+5nP2i0fNfYEMRc5JvF7BcHkn3U1fJ3En0Rm8fvwTo97cgKlCxn+VsPfM8KE5yRNJC7a2f7p90W1ph9l2GTgBkaISA8xh8HBtX1M43dw/0NQ7CPq6Xxc38a7iR2cTRNeihWQbbHMNwpi65QIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnoYrBCh1vGzBwvkpFy32KR/C0/t5bdwPjBogsSVqHz0o9JeVEb76x6GsEsAdbUP5O8sDbXeflzDFoy3iUz+UY5rZh5cZHp5ee2NaOnRKtKclRpaVcyQjRouomx9FaH4bLjUup/X09Vw/ZhcC0UYHyCZDZU6VbJA6237TQ1naWGVBgF6Nu32XiVt6uceNrfwiKzgMF/A0uwxzT6taf5tXlLnmnCYsV7mxNxPbtsT50nnLqw/DdBHRiI8i8bZhUBYwfqtzmrct+m+IlZffWCpa9ExFy0KV+Rfrs+H/TpGnh0f4WVK9U+GKK8hcuE8XhFCFY7/Sj6CamN22gi3b8iK+OwIDAQAB",
        'private_key' => 'MIIEowIBAAKCAQEAnoYrBCh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fcnLG7CZGqefmMzOC2Rwuveof1vcGK4XG70jZTvgbAxF1zgTC06MWkXFKbBb8riPAaGWssUmQurBXNnCHh64bzd7KyfxVk2Bdbve3Cpl2RN/mX1oWFIBZHjKEreH2D9xu/18ECgYAEN3QZc1J5CZdLOIaHhTRrlSarLE7Ysh3pXdfE+0qsfzgfuD3o/vmxS3d9vTSHjpiK/bsZ3GGSF1W7TLlXb3QdfqObyGusSfApgy26OwhINKzDd9EdgQjiczIphdgxY6YxZyK9wJ52uXXitKHCfhVal3xwALkYDEg7wJD6PBIC1QKBgGb0dXDy5DHx9zKyMCE2ggglKlzNtSJEskfbdS3ot8Qwa2v3+/Y1J3DINfpgNNzwGct7B83FAQsZ9GMSR2yhkWFa+SOJpjj7pL1d1tM7s2Ivs7XvmqPYn7yjvn/gtjLi574v9lE8pCJNCEa1Ni407Mkybm7IJMoDz9S7xyifTt2N'
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//    public function getParam(){
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
//        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2019011462952086";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://dc.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return string|void
     * user_id：用户ID,
     * type：1 课程购买  2 捐赠  3 打赏
     * price：打赏或捐赠的价格，当type为2或者3时传
     * activity_id：捐赠的活动ID，当type为2时，传此值
     */
    public function alipay()
    {
        extract(input());

        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }

//        $money = 0.01;
        if($params['type'] == 1){//支付
            $id = input('param.order_id');
            $data = Db::table('up_order')->where('order_id',$id)->find();
            if($data['order_id']==''){
                return json_encode(['status' => 0, 'msgsss' => '订单不存在']);
            }
            $this->body = '电池购买';
            $this->subject = '力伴换电电池购买';
            $this->total_amount = $data['order_user_pay'];
            $this->out_trade_no = $data['order_number'];

            $Info['ji_user_id'] = $user_id;
            $Info['ji_num'] = $data['order_number'];
            $Info['ji_title'] = '电池购买';
            $Info['ji_type'] =2;
            $Info['ji_from'] = 1;
            $Info['ji_money'] = $data['order_user_pay'];
            $Info['ji_time'] = date('Y-m-d H:i:s',time());
            $Info['ji_status'] = 1;
            Db::table('up_jilu')->insertGetId($Info);
        }elseif($params['type'] == 2){//充值
            $money = input('param.money');
            $order_number = date('YmdHis') . str_pad(mt_rand(1, 99999999), 6, '0', STR_PAD_LEFT).$user_id;
            $this->body = '电池充值';
            $this->subject = '力伴换电电池充值';
            $this->total_amount = $money;
            $this->out_trade_no = $order_number;

            $Info['ji_user_id'] = $user_id;
            $Info['ji_num'] = $order_number;
            $Info['ji_title'] = '充值';
            $Info['ji_type'] =1;
            $Info['ji_from'] = 1;
            $Info['ji_money'] = $money;
            $Info['ji_time'] = date('Y-m-d H:i:s',time());
            $Info['ji_status'] = 1;
            Db::table('up_jilu')->insertGetId($Info);
        }
//        $res1 = Db::table('up_order')->where('order_id',$id)->setField('order_type',1);
//        if($res1) {
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            return json_encode($respont);
//        } else {
//            return json_encode(['status' => 0, 'msgsss' => '生成订单失败，请联系管理员']);
//        }
    }
    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        $this->write_admin_log($getInfo);
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $dataOrder = array();
//                $dataOrder['order_trade_no'] = $getInfo['trade_no'];//支付宝返回的支付宝生成的订单号
//                $dataOrder['order_boos_get'] = $getInfo['receipt_amount'];//商家实际收的金额
//                $dataOrder['order_user_pay'] = $getInfo['buyer_pay_amount'];//用户实付金额
//                $dataOrder['order_ali_fund_bill_list'] = $getInfo['fund_bill_list'];//支付宝支付信息
                $dataOrder['order_paytime'] = $getInfo['gmt_payment'];//支付时间
                Db::startTrans();
                $dataOrder['order_status'] = 2;//1是未支付  2是支付成功未确认 3是已确认未完成  4是已完成
                $dataOrder['order_type'] = 1;
                $dataOrders['order_c_status'] = 2;
                $info = Db::table('up_order')->where('order_number',$num)->find();
                $userInfo = Db::table('up_u_user')->where('user_id',$info['order_userid'])->find();
                $dd = true;
                if($info['order_id']!=''){
                    $aa = Db::table('up_order')->where('order_number',$num)->update($dataOrder);
                    $cc = Db::table('up_jilu')->where('ji_num',$num)->setField('ji_status',2);
                    if($userInfo['user_type']==1){
                        $dataOrders['order_c_status'] = 2;
                        $abc= Db::table('up_order_children')->where('order_c_number',$num)->update($dataOrders);
                        if($abc){
                            $dd  = true;
                        }else{
                            $dd = false;
                        }
                    }
                    if($aa&&$cc&&$dd){
                        Db::commit();
                        //给自己推送
                        try{//新增
                            $user_id = (string)$userInfo['user_id'];
                            $str = '您编号为' . $num . '的订单已支付成功';
                            $this->Jpush(1, $user_id, $str, ['type' => '']);
                        }catch(\Exception $e){

                        }
                        //如果是用户订单，需给对应代理推送
                        if($userInfo['user_type'] == 1){
                            $daili_ids = Db::table('up_order_children')
                                ->where('order_c_number', $num)
                                ->field('order_c_daili_id')
                                ->select();
                            $ids = [];
                            foreach($daili_ids as $ke => $val){
                                $daili_id = (string)$val['order_c_daili_id'];
                                array_push($ids, $daili_id);
                            }
                            $this->Jpush(1, $ids, '您收到一个新订单', ['type' => '']);
                        }
                        die('success');
                    }else{
                        Db::rollback();//回滚
                        return 'error';
                    }
                }else{
                    $info1 = Db::table('up_jilu')->where('ji_num',$num)->find();
                    if($info1['ji_id']!=''){
                        $aa = Db::table('up_jilu')->where('ji_num',$num)->setField('ji_status',2);
                        $bb = Db::table('up_u_user')->where('user_id',$info1['ji_user_id'])->setInc('user_money',$info1['ji_money']);
                        if($aa&&$bb){
                            Db::commit();
                            die('success');
                        }else{
                            Db::rollback();//回滚
                            return 'error';
                        }
                    }
                }

            }
        }
    }
}